package fdoj.eventInvitations.servlet;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;

import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;

public class FacebookAPI {


	/**
	 * @param access_token 
	 * token pristupa
	 * @param request
	 * example: "me/friends?fields=name,id,email"
	 * @return
	 * JSONObject read from request
	 */
	public static JSONObject readInfo(String access_token,String request) {
		JSONObject retVal = null;
		try {
			String adresa = "https://graph.facebook.com/"+request+"&access_token="
					+ access_token;
			URL url = new URL(adresa);
			InputStreamReader reader = new InputStreamReader(url.openStream());
			JSONParser parser = new JSONParser();
			retVal = (JSONObject) parser.parse(reader);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return retVal;
	}
	
	public static String getURL(String appID,String redirectURL,String scopes){
		String retVal="https://www.facebook.com/dialog/oauth?client_id="
		+ appID+ "&redirect_uri=" + redirectURL
		+ "&scope="+scopes;
		return retVal;
	}
	
	public static String getAccessToken(String appID,String redirectURL,String appSecret,String code){
		String access_token=null;
		URL url;
		try {
			url = new URL("https://graph.facebook.com/oauth/access_token?client_id=" + appID + "&redirect_uri="
			+ redirectURL + "&type=user_agent&client_secret="
			+ appSecret + "&code=" + code);
		InputStreamReader isr = new InputStreamReader(
				url.openStream());
		BufferedReader br = new BufferedReader(isr);
		String response = br.readLine();
		access_token= response.split("=")[1];
		} catch (MalformedURLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return access_token;
	}

}
